package com.liusu.spider.test;


import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

public class HTTPPost {

    /**
     * URI
     * 统一资源标志符
     * Uniform Resource Identifier
     *
     * URL
     * Uniform Resource Locator
     * 统一资源定位器
     *
     * 发送带有参数的POST请求
     *
     *
     */
    @Test
    public void context(){

        CloseableHttpClient client = HttpClients.createDefault();

        String url = "http://yun.itheima.com/search";
        HttpPost post = new HttpPost(url);

        List<NameValuePair> list = new ArrayList<>();
        BasicNameValuePair kv1 = new BasicNameValuePair("so", "java");
        BasicNameValuePair kv2 = new BasicNameValuePair("type", "course");
        BasicNameValuePair kv3 = new BasicNameValuePair("realhash", "18fc53a52a033fe75f7d0542124ca8c0_fad6eabe086b983469eba3e6fae4b08a");
        list.add(kv1);
        list.add(kv2);
        list.add(kv3);

        UrlEncodedFormEntity entity = null;
        try {
            entity = new UrlEncodedFormEntity(list,"utf-8");


        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        post.setEntity(entity);

        try {
            CloseableHttpResponse response = client.execute(post);
            HttpEntity entity1 = response.getEntity();
            String html = EntityUtils.toString(entity1, "utf-8");
            System.out.println(html);
            response.close();
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
